replit <<
Previous Next >> part 2
part 1
顛倒數字
#include <stdio.h>
// 定義反轉數字的函式
int reverse(int n) {
int d, y = 0;
while (n) {
d = n % 10;
// 檢查溢位情況,以確保反轉後的數字仍在 int 範圍內
if ((n > 0 && y > (0x7fffffff - d) / 10) ||
(n < 0 && y < ((signed)0x80000000 - d) / 10)) {
return 0; // 如果溢位,則返回 0
}
y = y * 10 + d;
n = n / 10;
}
return y; // 返回反轉後的數字
}
int main(void)
{
int i = 678;
printf("原式: %d ", i);
printf("\n顛倒: %d ", reverse(i));
return 0;
}
replit <<
Previous Next >> part 2